package db

import (
	"encoding/json"
	"errors"
	"fmt"
	"log"
	"sort"
	"strconv"
	"strings"
	"ulcdkey/tool"
)

// 获取用户列表
func (this *User) CacheUsers() (err error) {
	rows, err := db.Query("select  id, userName, wxUserId, passWord, name, thumbAvatar, status, roleId, updateTime, time from user ;")
	if err != nil {
		return
	}
	tmp := make(map[int]*User)
	wxTmp := make(map[string]*User)

	defer rows.Close()
	for rows.Next() {

		u := new(User)

		err = rows.Scan(
			&u.Id,
			&u.UserName,
			&u.WxUserId,
			&u.PassWord,
			&u.Name,
			&u.ThumbAvatar,
			&u.Status,
			&u.RoleId,
			&u.UpdateTime,
			&u.Time)
		if err != nil {
			return
		}

		tmp[u.Id] = u
		wxTmp[u.WxUserId] = u
	}
	UserList = tmp
	WxUserList = wxTmp
	return
}

func (this *User) CheckUser(userName, passWord string) (u *User, err error) {

	for _, user := range UserList {

		if user.UserName != userName {
			continue
		}

		if user.PassWord != passWord {
			err = errors.New("密码不正确")
			return
		}

		if user.Status == 1 {
			err = errors.New("账号被禁止")
			return
		}

		// 登录成功
		u = user
		log.Println("CheckUser 登录成功:", userName)
		return
	}

	err = errors.New("用户名不存在")
	return
}

// 获取用户详情
func (this *User) GetUserById(uid int) (u *User, err error) {

	if UserList[uid] == nil {

		err = errors.New("非法用户Id")
		return
	}

	u = UserList[uid]
	if RolesList[u.RoleId] == nil {

		err = errors.New("非法角色Id")
		return
	}

	u.RoleName = RolesList[u.RoleId].Name
	u.PlatformAuth = RolesList[u.RoleId].PlatformAuth
	log.Println("GetUserInfo success:", u.UserName)
	return
}

// 通过微信用户id获取用户详情
func (this *User) GetUserByWxUserId(uid string) (u *User, err error) {
	if WxUserList[uid] == nil {
		err = errors.New("非法用户Id")
		return
	}

	u = WxUserList[uid]
	if RolesList[u.RoleId] == nil {
		err = errors.New("非法角色Id")
		return
	}

	u.RoleName = RolesList[u.RoleId].Name
	u.PlatformAuth = RolesList[u.RoleId].PlatformAuth
	log.Println("GetUserInfo success:", u.UserName)
	return
}

//根据用户id获取用户角色信息
func (this *User) GetRoleInfoByUid(uid int) (r *Role, err error) {
	nUser, err := this.GetUserById(uid)
	nRole := new(Role)

	r, err = nRole.GetRoleById(nUser.RoleId)
	return
}

//获取用户权限的路由
func (this *User) GetMenuByRole(uid int) (ms []*Menus, err error) {

	//log.Println("GetMenuByRole  uid:", uid)
	role := new(Role)
	r, err := role.GetRoleByUserId(uid)

	if err != nil {

		log.Println("GetMenuByRole err:", err.Error())
		return
	}
	//log.Println("GetMenuByRole  r:", r.MenuAuth)
	mIds := strings.Split(r.MenuAuth, ",")

	//log.Println("GetMenuByRole  mIds:", mIds)
	rows, err := db.Query("select id, `name`,urlJson, pid from menu order by menuOrder")
	if err != nil {
		return
	}

	defer rows.Close()
	for rows.Next() {
		m := new(Menus)
		err = rows.Scan(&m.Id, &m.Name, &m.UrlJson, &m.Pid)
		if err != nil {
			return
		}
		if tool.IsExist(mIds, strconv.Itoa(m.Id)) {
			ms = append(ms, m)
		}
	}

	//log.Println("GetMenuByRole ms:", ms)
	return
}

// 获取用户列表
func (this *User) GetUsers() (us []*User, err error) {

	us = []*User{}

	keys := []int{}
	for id, _ := range UserList {
		keys = append(keys, id)
	}

	sort.Ints(keys)

	for _, id := range keys {

		u := UserList[id]

		r := RolesList[u.RoleId]
		if r == nil {
			continue
		}

		u.RoleName = r.Name
		us = append(us, u)
	}
	return
}

// 修改用户
func (this *User) ModUser(info *tool.VisitUserInfo) (err error) {

	old, err := this.GetUserById(this.Id)
	if err != nil {
		return
	}

	_, err = db.Exec("update user set `name` = ?,roleId = ?,`status` = ?,updateTime = now() where id = ?",
		this.Name,
		this.RoleId,
		this.Status,
		this.Id)

	if err != nil {
		return
	}

	// 记录日志
	nb, _ := json.Marshal(this)
	ob, _ := json.Marshal(old)

	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, Platform: info.Platform, ActionType: LogActionType.Update, Module: "用户管理", OldContent: string(ob), NewContent: string(nb)}
	serverLog.RecordLog()

	//更新用户权限map
	err = this.CacheUsers()

	if err != nil {

		log.Println("ModUser ", err)
		return
	}
	return
}

// 校验用户是否有该游戏的权限
func (this *User) CheckUserGameRole(gameId int) (flag bool) {
	userInfo := UserList[this.Id]
	roleInfo := RolesList[userInfo.RoleId]
	if roleInfo.GameAuth == "all" {
		return true
	}
	gameIdStr := fmt.Sprint(gameId)

	gameAuthArr := strings.Split(roleInfo.GameAuth, ",")
	for _, gId := range gameAuthArr {
		if gameIdStr == gId {
			return true
		}
	}
	return
}
